package org.szgb.console.sys.department.service;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.szgb.console.sys.department.entity.SysDepartment;
import org.szgb.console.sys.department.mapper.SysDepartmentMapper;
import org.szgb.console.utils.Page;
import org.szgb.console.utils.UUIDUtil;

import java.util.List;

@Slf4j
@Service
public class SysDepartmentService {
    private final SysDepartmentMapper sysDepartmentMapper;

    @Autowired
    public SysDepartmentService(SysDepartmentMapper sysDepartmentMapper) {
        this.sysDepartmentMapper = sysDepartmentMapper;
    }

    @Transactional(readOnly = true)
    public SysDepartment get(String id) {
        return sysDepartmentMapper.get(id);
    }

    @Transactional(readOnly = true)
    public List<SysDepartment> findList(SysDepartment sysDepartment) {
        if (sysDepartment != null && sysDepartment.getPageDto() != null) {
            Page<SysDepartment> page = new Page<>(sysDepartment.getPageDto());
            page.setFirst((page.getPageNo() - 1) * page.getPageSize());
            sysDepartment.setPage(page);
        }
        return sysDepartmentMapper.findList(sysDepartment);
    }

    @Transactional(readOnly = true)
    public Integer getCount(SysDepartment sysDepartment) {
        return sysDepartmentMapper.getCount(sysDepartment);
    }

    @Transactional()
    public void save(SysDepartment sysDepartment) {
        // 检查实体对象的ID是否为null，判断是否为新实体
        if (sysDepartment.getId() == null || sysDepartment.getId().isEmpty()) {
            // 对于新实体，设置创建者信息
            sysDepartment.setCreatedBy(sysDepartment.getUpdatedBy());
            // 添加UUID
            sysDepartment.setId(UUIDUtil.getUUID());
            // 执行插入操作
            sysDepartmentMapper.insert(sysDepartment);
            // 返回成功插入的信息
        } else {
            // 执行更新操作
            sysDepartmentMapper.update(sysDepartment);
        }
    }

    @Transactional
    public void delete(String ids) {
        sysDepartmentMapper.delete(ids.split(","));
    }
}
